package com.shawn.springboot.integeration.netty.client.initializer.factory;

import com.shawn.springboot.integeration.netty.client.initializer.AbstractChannelInitializer;
import com.shawn.springboot.integeration.netty.client.initializer.DefaultChannelInitializer;
import com.shawn.springboot.integeration.netty.exception.ApiException;
import com.shawn.springboot.integeration.netty.model.ServerAddress;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangjian
 * @title: InitializerFactory
 * @projectName 12-springboot学习
 * @description: 通道设置工厂
 * @date 2021/4/289:46
 */
@Slf4j
public final class InitializerFactory {

    private static final Map<String,Class<? extends AbstractChannelInitializer>> CONTAINER = new HashMap<>();

    private static final String KEY_JOINER = "_";

    /**
     * 连接通道设置集合,不同的设备可能需要实现不同的连接通道设置
     * 这边Key是以服务端IP + 下划线 + 端口拼接而成
     */
    static {
        CONTAINER.put("127.0.0.1_8888", DefaultChannelInitializer.class);
    }

    /**
     * 获取连接通道设置
     */
    public static ChannelInitializer<SocketChannel> get(ServerAddress serverAddress) throws ApiException {
        String key = serverAddress.getIp() + KEY_JOINER + serverAddress.getPort().toString();
        return get(CONTAINER.get(key));
    }


    private static ChannelInitializer<SocketChannel> get(Class<? extends AbstractChannelInitializer> classname) throws ApiException {
        try {
            return (ChannelInitializer<SocketChannel>) Class.forName(classname.getName()).newInstance();
        } catch (InstantiationException|IllegalAccessException|ClassNotFoundException e) {
            throw new ApiException("获取通道设置失败",e);
        }
    }

}
